package com.dmcb.common.business.utils;

import com.dmcb.common.web.conversion.JsonResult;
import com.dmcb.common.web.conversion.MapJsonResult;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * Json工具类
 * Created by long on 2015/11/9.
 */
public class JsonUtil {

    // 直接将一个json转化为对象
    public static Map<String,Object> getResult(String json) {
        if (StringUtils.isBlank(json)) {
            return null;
        }
        Map<String,Object> map = (Map) readJsonObject(json, Map.class);
        if (map == null) {
            return null;
        }
        return map ;
    }

    // 直接将一个json转化为对象
    public static List<Map<String, String>> readListResult(String json) {
        if (StringUtils.isBlank(json)) {
            return new ArrayList<Map<String, String>>();
        }
        MapJsonResult mapJsonResult = (MapJsonResult) readJsonObject(json, MapJsonResult.class);
        Map map = (Map) mapJsonResult.getData();
        List list = (List) map.get("list");
        if (map == null || map.get("list") == null) {
            return new ArrayList<Map<String, String>>();
        }
        List<Map<String, String>> maps = new ArrayList<Map<String, String>>();
        for (Object obj : list) {
            maps.add((Map) obj);
        }
        return list;
    }

    // 直接将一个json转化为对象
    public static JSONArray readJsonArray(String json) {
        return JSONArray.fromObject(json); // 首先把字符串转成 JSONArray  对象
    }

    // 直接将一个json转化为对象
    public static Object readJsonObject(String json, Class cls) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(json,
                    cls);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new JsonResult();
    }

}
